import { message } from 'antd';
import React, { useRef } from 'react';
import { SUCCESS_CODE } from '@/utils/request';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ModalForm } from '@ant-design/pro-form';
import type { AuthRoleEditItem, AuthRoleTableListItem } from '@/pages/Auth/AuthRole/data';
import AuthRoleConfiguration from './AuthRoleConfiguration';
import { updateAdminRoles } from '../service';

interface EditFormProps {
  item: AuthRoleTableListItem;
  onSubmit: (values: AuthRoleEditItem) => void;
  modalVisible: boolean;
  onVisibleChange: (visible: boolean) => void;
}

const EditForm: React.FC<EditFormProps> = (props) => {
  const { onSubmit, onVisibleChange, modalVisible, item } = props;

  const formRef = useRef<ProFormInstance>();
  formRef.current?.setFieldsValue(item);
  const onModalOk = async () => {
    const fieldsValue = (await formRef.current?.validateFields()) as AuthRoleEditItem;

    fieldsValue.id = item?.id;

    const hide = message.loading('正在修改');

    try {
      const res = await updateAdminRoles({
        id: fieldsValue?.id,
        roles: fieldsValue?.access,
      });
      if (res.code === SUCCESS_CODE) {
        hide();
        message.success('修改成功');
        onSubmit(fieldsValue);
      } else {
        message.error(res.message || '修改失败');
      }
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      onSubmit(fieldsValue);
      return false;
    }
  };
  return (
    <ModalForm
      title="修改账号角色"
      visible={modalVisible}
      formRef={formRef}
      width={600}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      onVisibleChange={(value) => {
        onVisibleChange(value);
      }}
      onFinish={onModalOk}
    >
      {/* <ProFormText name="name" label="角色名称" rules={[{ required: true, message: '必填' }]} /> */}

      <ProForm.Item name="access" label="权限配置">
        <AuthRoleConfiguration
          tenant_id={item?.tenant_id || ''}
          // defaultValue={data}
          id={item?.id}
          // onChange={async (values) => {
          // }}
        />
      </ProForm.Item>
    </ModalForm>
  );
};
export default EditForm;
